import axios from 'axios'
import { Toast } from 'vant'
import { delToken, getToken } from './storage'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://interview-api-t.itheima.net',
  timeout: 6000
})

request.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

request.interceptors.response.use((res) => {
  return res.data
}, (error) => {
  if (error.response) {
    if (error.response.status === 401) {
      delToken()
      router.replace('/login')
    } else {
      Toast(error.response.data.message)
    }
    return Promise.reject(error)
  }
})

export default request
